package com.wuyan.web.auth.api;

import com.wuyan.web.auth.entity.PubViewAccount;
import com.wuyan.web.auth.form.PubViewAccountForm;
import com.wuyan.web.auth.service.api.WuyanPubViewAccountService;
import com.wuyan.web.base.aop.ApiLogAnnotation;
import com.wuyan.web.base.helper.BaseApi;
import com.wuyan.web.base.helper.rep.RepBody;
import com.wuyan.web.base.helper.rep.RepCodeEnum;
import com.wuyan.web.base.helper.rep.RepHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/register")
public class RegisterApi extends BaseApi implements RepHelper {

    @Autowired
    private WuyanPubViewAccountService wuyanPubViewAccountService;

    /**
     * 注册
     *
     * @param form 注册信息
     * @return RepBody<Boolean>
     */
    @PostMapping
    @ApiLogAnnotation(name = "register:create")
    public RepBody<PubViewAccount> create(HttpServletRequest request,
                                          @RequestBody Map<String, Object> form) {
        String ak = form.containsKey("ak") ? form.get("ak").toString() : "";
        String code = getAttr(request, "register-" + ak, String.class, true);
        if (null == code) {
            return error(RepCodeEnum.ERR_LOGIN_VERIFY_INVALID);
        }

        if (!code.equals(form.get("code").toString().toUpperCase())) {
            return error(RepCodeEnum.ERR_LOGIN_VERIFY);
        }

        String username = form.containsKey("key") ? form.get("key").toString() : "";
        String password = form.containsKey("pwd") ? form.get("pwd").toString() : "";

        PubViewAccountForm accountForm = PubViewAccountForm.builder()
                .username(username)
                .password(password)
                .email(username)
                .status(1)
                .source(0)
                .build();

        return wuyanPubViewAccountService.create(accountForm);
    }
}
